A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
-bash/zsh: if ifand not found # Windows (WSL2) sudo apt-get update sudo apt-get install execline # Debian apt-get install execline # Ubuntu apt-get install execline # Alpine apk add execline # Kali Linux apt-get install execline # Dockerfile dockerfile.run/if # Docker docker run cmd.cat/if if
if 执行测试命令列表,如果其返回状态为 0
(成功),则执行后续命令列表。
虽然 if 最常与测试一起使用以返回 True / False 判断,但它可以与任何返回退出代码 0 表示成功的命令一起使用。
如果 test-commands
返回非零状态,则依次执行每个 elif
列表,如果其退出状态为 0,则执行相应的 more-consequents
并完成命令。
如果存在 else alternative-consequents,并且最后的 if 或 elif 子句中的最后一个命令具有非零退出状态,则执行 alternative-consequents。
对于简单的比较,一个简洁的替代方法是使用 test 和条件运算符 && 而不是 IF。返回状态是最后执行的命令的退出状态,如果没有条件测试为真,则返回零。
这是 BASH Shell 内置命令,要从 bash 提示符类型显示本地语法:help if。
if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi # 单行 if test-commands; then consequent-commands; fi
execline 是一种(非交互式)脚本语言,类似于 sh,但其语法与传统的 Shell 语法截然不同。execlineb 程序旨在用作文本文件的解释器;其他命令本质上是在 execlineb 脚本内部使用的。execline 的功能与 Shell 一样强大。
if 如果条件命令的退出状态为零,则执行指定的命令:
if condition_command; then echo "Condition is true"; fi
if 如果条件命令的退出状态不为零,则执行指定的命令:
if ! condition_command; then echo "Condition is true"; fi
if 如果条件命令的退出状态为零,则执行第一个指定的命令,否则执行第二个指定的命令:
if condition_command; then echo "Condition is true"; else echo "Condition is false"; fi
if 检查文件是否存在:
if [[ -f path/to/file ]]; then echo "Condition is true"; fi
if 检查目录是否存在:
if [[ -d path/to/directory ]]; then echo "Condition is true"; fi
if 检查文件或目录是否存在:
if [[ -e path/to/file_or_directory ]]; then echo "Condition is true"; fi
if 检查变量是否定义:
if [[ -n "$variable" ]]; then echo "Condition is true"; fi
if 列出所有可能的条件 test 是 [ 的别名;两者通常与 if
一起使用:
man [